<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        v-model.trim="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </form>

    <!-- 搜索结果列表 -->
    <search-result v-if="isResultShow" :searchText="searchText" />

    <!-- 搜索建议 -->
    <search-suggstion
      v-else-if="searchText"
      :searchText="searchText"
      @searchFn="onSearch"
    />

    <!-- 搜索历史 -->

    <search-history
      v-else
      @removeAllHis="removeAllHisFn"
      @removeHis="removeHisFn"
      @onSearch="onSearch"
      :searchHistories="searchHis"
    />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import SearchSuggstion from './components/search-suggstion.vue'
import { mapState, mapMutations } from 'vuex'
export default {
  name: '',
  props: {},
  components: { SearchResult, SearchSuggstion, SearchHistory },
  computed: {
    ...mapState(['searchHis'])
  },
  created () {},
  mounted () {},
  watch: {},
  data () {
    return {
      searchText: '',
      isResultShow: false
    }
  },
  methods: {
    ...mapMutations(['setHis', 'removeAllHis', 'removeHis']),
    onSearch (val) {
      //   console.log(val)
      // 将联想建议面板的数据同步到输入框
      this.searchText = val
      // 加入搜索历史
      this.setHis(val)

      this.isResultShow = true
    },
    removeAllHisFn () {
      this.removeAllHis()
    },
    // 删除某条历史记录
    removeHisFn (ind) {
      this.removeHis(ind)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 106px;
  // 将搜索框固定在头部
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
